package com;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.*;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.FilterPredicate;

public class Voteupdate extends HttpServlet{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -378626842616294902L;

	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		resp.setContentType("text/plain");
		
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
        Query query = new Query("Post");
        Filter filter = new FilterPredicate("valid",FilterOperator.EQUAL,"1");
        query.setFilter(filter);
        List<Entity> results = datastore.prepare(query).asList(FetchOptions.Builder.withDefaults());
        
        resp.getWriter().println("Updating votes ...");
        
        
        Date today = new Date();
        for (Entity post: results){
        	Date d = (Date)post.getProperty("date");
        	Long i = (Long)post.getProperty("timelimit");
        	long l = today.getTime() - (d.getTime() + i);
        	if(l>0){
        		post.setProperty("valid", "0");
        		datastore.put(post);
        	}else{
            	resp.getWriter().println(d.toString()+" "+i.toString());
        	}
        }
        resp.sendRedirect("/");
	}
}
